package com.wf.smartcomm.server.weixin.action;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.wf.smartcomm.server.bean.House;
import com.wf.smartcomm.server.bean.User;
import com.wf.smartcomm.server.bean.Village;
import com.wf.smartcomm.server.client.action.BaseAction;
import com.wf.smartcomm.server.service.HouseService;
import com.wf.smartcomm.server.service.UserService;
import com.wf.smartcomm.server.service.VillageService;
import com.wf.smartcomm.server.util.ConstantUtils;
import com.wf.smartcomm.server.util.PushUtils;
import com.wf.smartcomm.server.util.StringUtil;
import com.wf.smartcomm.server.weixin.util.WeixinUtil;

@Service
@Scope("prototype")
public class BindAction extends BaseAction {

	@Resource
	private VillageService villageServiceImpl;
	
	@Resource
	private HouseService houseServiceImpl;
	
	@Resource
	private VillageService vilageServiceImpl;
	
	@Resource
	private UserService userServiceImpl;
	
	public String toBind(){
		String step = request.getParameter("step");
		if (StringUtil.isEmpty(step)) {
			HttpSession session = request.getSession();
			User user = (User) session.getAttribute("user");
			if (user != null) {
				return "success";
			}else {
				/*Cookie[] cookies = request.getCookies();
				if (cookies != null && cookies.length > 0) {
					for(Cookie cookie : cookies){
			            if(cookie.getName().equals("userId")){
			            	String userId = cookie.getValue();
			            	user = userServiceImpl.getUserById(userId);
			    			session.setAttribute("user",user);
			    			return "success";
			            }
			        }
				}*/
				String code = request.getParameter("code");
				logger.info("code--------->"+code);
				String oauth_full_url ="";
				if (PushUtils.isDevEnv) {
					oauth_full_url=oauth_base_url_dev+"&code="+code+"&grant_type=authorization_code";
				}else {
					oauth_full_url=oauth_base_url_gen+"&code="+code+"&grant_type=authorization_code";
				}
				JSONObject jsonObject = WeixinUtil.httpRequest(oauth_full_url, "GET", null);
				if (jsonObject != null) {
					logger.info(jsonObject);
					String openId = jsonObject.getString("openid");
					logger.info("openId-------->:"+openId);
					user = userServiceImpl.getUserByOpenId(openId);
					if (user == null) {
						Cookie cookie = new Cookie("openId", openId);
						cookie.setMaxAge(3600*24*30*12*2);
						response.addCookie(cookie);
						return "loginlogin";
					}
					Cookie cookie = new Cookie("userId", user.getObjectId());
					cookie.setMaxAge(3600*24*30*12*2);
					response.addCookie(cookie);
					session.setAttribute("user", user);
					return "success";
					//判断该openid是否注册，未注册转注册页面
					//同意后获取code 换acceess_token ,openid
					//将access_token和过期时间存入数据库
					//存入session 和 cookie
				}else {
					logger.info("jsonObject is null");
					return "login";
				}
			}
		}
		return "success";
	}
	
	public void searchVillage() throws IOException{
		villageServiceImpl.queryByKey(request.getParameter("villageName"),page);
		request.getSession().setAttribute("villages", page.getDataList());
		printJsonData(200);
	}
	
	public void selectedVillage() throws IOException{
		String vid = request.getParameter("vid");
		Village village = vilageServiceImpl.get(vid);
		HttpSession session = request.getSession();
		houseServiceImpl.listRegion(village, page);
		session.setAttribute("village", village);
		session.setAttribute("regions", page.getDataList());
		printJsonData(200);
	}
	
	public void selectedRegion() throws IOException {
		String vid = request.getParameter("vid");
		String region = request.getParameter("region");
		houseServiceImpl.listBuilding(vid, region, page);
		printJsonData(page.getDataList());
	}
	
	public void selectedBuilding() throws IOException{
		String vid = request.getParameter("vid");
		String region = request.getParameter("region");
		String building = request.getParameter("building");
		houseServiceImpl.listEntrance(vid, region, building, page);
		printJsonData(page.getDataList());
	}
	
	public void selectedEntrance(){
		try {
			String vid = request.getParameter("vid");
			String region = request.getParameter("region");
			String building = request.getParameter("building");
			String entrance = request.getParameter("entrance");
			houseServiceImpl.listBySelect(new Village(vid), region, building, entrance, page);
			printJsonData(gson.toJson(page.getDataList()));
		} catch (Exception e) {
			System.out.println(e.getStackTrace());
			
			System.out.println("----------------------------------------");
			
			System.out.println(e.getMessage());
			
			StringBuilder trace = new StringBuilder();
			trace.append(e.toString()).append(System.getProperty("line.separator"));
			for (StackTraceElement element : e.getStackTrace()) {
				trace.append(element.toString()).append(System.getProperty("line.separator"));
			}
			
			System.out.println(trace.toString());
		}
	}
	
	public void bind() throws IOException{
		String userId = request.getParameter("userId");
		String houseId = request.getParameter("houseId");
		House house = houseServiceImpl.getById(houseId);
		if (house.getUser() != null) {
			printJsonData(201);
			return;
		}
		
		User user = (User) request.getSession().getAttribute("user");
		
		if (user == null) {
			user = userServiceImpl.getUserById(userId);
		}
		
		if (house.getId().equals(user.getId())){
			user.setType(ConstantUtils.USER_TYPE_PRIMARY);
			if (user.getLoginVillage() == null) {
				user.setLoginVillage(house.getVillage());
			}else if (!user.getLoginVillage().getObjectId().equals(house.getVillage().getObjectId())) {
				userServiceImpl.addVillage(user, house.getVillage());
		    }
		}
		
		userServiceImpl.update(user);
		house.setUser(user);
		house.setReceiver(user.getObjectId());
		houseServiceImpl.update(house);
		houseServiceImpl.addUser(house.getObjectId(), user.getObjectId());
		printJsonData(200);
	}
}
